package com.screen.screendisplay.service.impl.ne;

import com.screen.screendisplay.entity.ne.NeProdoperEastPrice;
import com.screen.screendisplay.mapper.ne.NeProdoperEastPriceMapper;
import com.screen.screendisplay.service.ne.NeProdoperEastPriceService;
import com.screen.screendisplay.vo.ne.NeEastElectricPriceVO;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 蒙东实时电价表 服务实现类
 * </p>
 *
 * @author xuesong
 * @since 2025-08-23
 */
@Service
public class NeProdoperEastPriceServiceImpl extends ServiceImpl<NeProdoperEastPriceMapper, NeProdoperEastPrice> implements NeProdoperEastPriceService {

    @Autowired
    private NeProdoperEastPriceMapper neProdoperEastPriceMapper;

    @Override
    public List<NeEastElectricPriceVO> getEastElectricPrice(Integer year) {
        List<NeProdoperEastPrice> dataList = neProdoperEastPriceMapper.selectDailyPriceData(20);
        
        // 按日期分组，每组包含光伏和风电电价数据
        Map<String, List<NeProdoperEastPrice>> groupedData = dataList.stream()
                .collect(Collectors.groupingBy(data -> data.getYear() + "-" + data.getMonth() + "-" + data.getDay()));
        
        List<NeEastElectricPriceVO> resultList = new ArrayList<>();
        
        // 遍历分组数据，构建VO对象
        groupedData.entrySet().stream()
                .sorted((e1, e2) -> e2.getKey().compareTo(e1.getKey())) // 按时间倒序
                .limit(10) // 只取最近10天
                .forEach(entry -> {
                    List<NeProdoperEastPrice> dayData = entry.getValue();
                    
                    NeEastElectricPriceVO vo = new NeEastElectricPriceVO();
                    
                    // 设置年、月、日、日期（从第一条记录获取）
                    if (!dayData.isEmpty()) {
                        NeProdoperEastPrice firstData = dayData.get(0);
                        vo.setYear(firstData.getYear());
                        vo.setMonth(firstData.getMonth());
                        vo.setDay(firstData.getDay());
                        vo.setDate(firstData.getDate());
                    }
                    
                    // 分别设置光伏和风电电价
                    for (NeProdoperEastPrice data : dayData) {
                        if (data.getPriceType() == 0) { // 光伏电价
                            vo.setSolarPrice(data.getPrice());
                        } else if (data.getPriceType() == 1) { // 风电电价
                            vo.setWindPrice(data.getPrice());
                        }
                    }
                    
                    resultList.add(vo);
                });
        
        return resultList;
    }
}
